/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package chipchipclient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.sound.sampled.ReverbType;
import sun.reflect.generics.visitor.Reifier;

/**
 *
 * @author Tri
 */
public class ClientController implements Runnable {
    private DataOutputStream dos;
    private DataInputStream dis;
    private BufferedReader br;
    private Socket socket;
    private Boolean isConnected;
    private int port;
    private String host;
    private JSONParser parser;
    public ClientController(String host, int port) {
        socket = null;
        dos = null;
        dis = null;
        isConnected = false;
        this.port = port;
        this.host = host;
        parser = JSONParser.getInstance();
    }
    
    public void connect() {
        try {
            this.socket = new Socket(host, port);
            this.dos = new DataOutputStream(this.socket.getOutputStream());
            this.isConnected = true;
            doSendMessage(new CCMessage(1000, "HELLO WORLD"));
            listenForMessages();   
        } catch (Exception ex) {
            ex.printStackTrace();
        }
     }
    
    public void doSendMessage(CCMessage msg) throws IOException {
        Message m = new Message(1001);
            m.putString("HELLO WORLD");
            byte[] data = m.getBuffer();
            dos.writeInt(data.length + 1);
            dos.writeByte(m.id);
            dos.write(data);
            dos.flush();
            
            m.cleanup();
    }
    
    private void listenForMessages() throws IOException {
        dis = new DataInputStream(socket.getInputStream());
        while(true) {
           int dataLength = dis.readInt();
           int cmdID = dis.readByte();
           byte[] data = new byte[dataLength - 1];
           dis.read(data);
           Message m = new Message(data);
           
        }
        /*
         BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
    String cominginText = "";
    try
    {
        cominginText = in.readLine ();
        System.out.println (cominginText);
    }
    catch (IOException e)
    {
        //error ("System: " + "Connection to server lost!");
        System.exit (1);
        break;
    }
}
         */
        
        /*
        while(true) {
//            if(dis.available() < 5) {
//                return;
//            }
            // Do dai cua message
            int dataLength = dis.readInt();
            if(dis.available() < dataLength) {
                dis.reset();
                return;
            }
            int commandID = dis.readByte();
            // Data cua message
            // Ở đây -1 là vì khi ta ghi message trên server gửi xuống, ta có ghi thêm 
            // 1 byte để ám chỉ commandID ở phía đầu message. Do đó dataLength - 1 là phần
            // Data của message
            byte[] decoded = new byte[dataLength - 1];
            dis.read(decoded);
            Message msg = new Message(decoded);
            System.out.println("ID: " + commandID);
            System.out.println("Data: " + msg.reader().readUTF());
        }
        */
    }
    
    private void receiveMessage(String jsonStr) {
        CCMessage receivedMsg = parser.fromJSON(jsonStr);
        System.out.println("CommandID: " + receivedMsg.getCommandID());
        System.out.println("Data: " + receivedMsg.getContent());
    }
    
    public void cleanUp() throws IOException {
        if(dos != null) {
            dos.close();
        }
        if(dis != null) {
            dis.close();
        }
    }

    @Override
    public void run() {
        connect();
    }
}
